package com.kwan.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;


import com.youth.banner.util.LogUtils;

import java.util.ArrayList;
import java.util.HashMap;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

/**
 * @Author tzc
 * @Time 2022/10/13 0013
 * Describe viewpage2滑动处理方案 此类用于解决 ViewPager2  嵌套 ViewPager2 或者 RecyclerView 等相互嵌套的冲突问题，
 * <p>
 * 改造后解决两个问题：
 * 1.RecyclerView必须是NestedScrollableHost的第一个子View。
 * 2.只解决同方向的滑动冲突。
 * https://blog.csdn.net/weixin_44139159/article/details/123546494
 */
public class NestedScrollableHost extends FrameLayout {
	protected final String TAG = this.getClass().getSimpleName();
	/**
	 * 判断当前的ViewPager2与RecyclerView的滑动方向是否一致
	 */
	private boolean isChildHasSameDirection;
	private int touchSlop;
	private float initialX;
	private float initialY;
	private HashMap _$_findViewCache;

	private final ViewPager2 getParentViewPager() {
		ViewParent var10000 = this.getParent();
		if (!(var10000 instanceof View)) {
			var10000 = null;
		}

		View v;
		for (v = (View) var10000; v != null && !(v instanceof ViewPager2); v = (View) var10000) {
			var10000 = v.getParent();
			if (!(var10000 instanceof View)) {
				var10000 = null;
			}
		}

		View var2 = v;
		if (!(v instanceof ViewPager2)) {
			var2 = null;
		}

		return (ViewPager2) var2;
	}

	private final View getChild() {
		return getChildRecyclerView(this);
	}

	/**
	 * 我希望NestedScrollableHost无论下层布局如何，
	 * 都能找到其中的RecyclerView，
	 * 那么仅需提供一个遍历子View的方法
	 *
	 * @param view
	 * @return
	 */
	public View getChildRecyclerView(View view) {
		ArrayList<View> unvisited = new ArrayList<>();
		unvisited.add(view);

		while (!unvisited.isEmpty()) {
			View child = unvisited.remove(0);
			if (child instanceof RecyclerView) {
				return child;
			}
			if (!(child instanceof ViewGroup)) {
				continue;
			}
			ViewGroup viewGroup = (ViewGroup) child;
			for (int i = 0; i < viewGroup.getChildCount(); i++) {
				unvisited.add(viewGroup.getChildAt(i));
			}
		}
		return null;
	}

	private final boolean canChildScroll(int orientation, float delta) {
		boolean var5 = false;
		int direction = -((int) Math.signum(delta));
		View var10000;
		boolean var6 = false;
		switch (orientation) {
			case 0:
				var10000 = this.getChild();
				var6 = var10000 != null ? var10000.canScrollHorizontally(direction) : false;
				break;
			case 1:
				var10000 = this.getChild();
				var6 = var10000 != null ? var10000.canScrollVertically(direction) : false;
				break;
			default:
				// throw (Throwable)(new IllegalArgumentException());
		}

		return var6;
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent e) {
		this.handleInterceptTouchEvent(e);
		return super.onInterceptTouchEvent(e);
	}

	private final void handleInterceptTouchEvent(MotionEvent e) {
		ViewPager2 var10000 = this.getParentViewPager();

		if (var10000 != null) {
			//子布局滑动方向
			int orientation = isChildHasSameDirection ? var10000.getOrientation() : var10000.getOrientation() ^ 1;
			//LogUtils.e(TAG,"orientation="+orientation+"|canChildScroll="+(this.canChildScroll(orientation, -1.0F) || this.canChildScroll(orientation, 1.0F)));
			if (this.canChildScroll(orientation, -1.0F) || this.canChildScroll(orientation, 1.0F)) {
				if (e.getAction() == 0) {
					this.initialX = e.getX();
					this.initialY = e.getY();
					this.getParent().requestDisallowInterceptTouchEvent(true);
				} else if (e.getAction() == 2) {
					float dx = e.getX() - this.initialX;
					float dy = e.getY() - this.initialY;
					//子布局是否是横向布局
					boolean isVpHorizontal = orientation == 0;
					boolean var8 = false;
					float scaledDx = Math.abs(dx) * (isVpHorizontal ? 0.5F : 1.0F);
					boolean var9 = false;
					float scaledDy = Math.abs(dy) * (isVpHorizontal ? 1.0F : 0.5F);
					if (scaledDx > (float) this.touchSlop || scaledDy > (float) this.touchSlop) {
						//LogUtils.e(TAG,"isVpHorizontal="+isVpHorizontal+"|scaledDy="+scaledDy+"|scaledDx="+scaledDx+"|canChildScroll="+this.canChildScroll(orientation, isVpHorizontal ? dx : dy));
						//横向布局上下滑 或纵向布局左右滑 监听给viewpage2
						if ((isVpHorizontal && scaledDy > scaledDx) || (!isVpHorizontal && scaledDx > scaledDy)) {
							this.getParent().requestDisallowInterceptTouchEvent(false);
						} else {//其他情况都给子滑动组件
							this.getParent().requestDisallowInterceptTouchEvent(true);
						}
//                        else if (this.canChildScroll(orientation, isVpHorizontal ? dx : dy)) {
//                            this.getParent().requestDisallowInterceptTouchEvent(true);
//                        } else {
//                            this.getParent().requestDisallowInterceptTouchEvent(false);
//                        }
					}
				}

			}
		}
	}

	public NestedScrollableHost(Context context) {
		super(context);
		ViewConfiguration var10001 = ViewConfiguration.get(this.getContext());
		this.touchSlop = var10001.getScaledTouchSlop();
	}

	public NestedScrollableHost(Context context, @Nullable AttributeSet attrs) {
		super(context, attrs);
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.NestedScrollableHost);
		//与父级方向相同 true .相反 false
		isChildHasSameDirection = a.getBoolean(R.styleable.NestedScrollableHost_sameDirectionWithParent, false);
		a.recycle();
		ViewConfiguration var10001 = ViewConfiguration.get(this.getContext());
		this.touchSlop = var10001.getScaledTouchSlop();
	}

	public View _$_findCachedViewById(int var1) {

		if (this._$_findViewCache == null) {
			this._$_findViewCache = new HashMap();
		}

		View var2 = (View) this._$_findViewCache.get(var1);
		if (var2 == null) {
			var2 = this.findViewById(var1);
			this._$_findViewCache.put(var1, var2);
		}

		return var2;
	}

	public void _$_clearFindViewByIdCache() {
		if (this._$_findViewCache != null) {
			this._$_findViewCache.clear();
		}

	}
}